package com.bwie.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @author lenovo
 */
@Configuration
public class GatewayConfig implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();

        String ip = request.getRemoteAddress().getAddress().toString();
        String url = request.getPath().toString();

        if (url.contains("/user/sendCode")) {
            System.out.println("放行验证码接口");
            return chain.filter(exchange);
        }

        if (url.contains("/user/codeLogin")) {
            System.out.println("放行验证码登录接口");
            return chain.filter(exchange);
        }

        if (url.contains("/user/login")) {
            System.out.println("放行密码登录接口");
            return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst("token");

        if (token == null) {
            System.out.println("用户未登录");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        Claims claims = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody();
        Integer userId = claims.get("id", Integer.class);

        String redisToken = stringRedisTemplate.opsForValue().get("token:" + userId);

        if (redisToken == null) {
            System.out.println("token 过期");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        if (!redisToken.equals(token)) {
            System.out.println("异地登录");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        Long expire = stringRedisTemplate.getExpire("token:" + userId, TimeUnit.MINUTES);
        if (expire < 30) {

            stringRedisTemplate.expire("token:" + userId, 30, TimeUnit.MINUTES);
        }


        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
